# 设置 PROTO 生成路径
set(GENERATE_DIR ${PROJECT_SOURCE_DIR}/generated)
if (EXISTS "${GENERATE_DIR}" AND IS_DIRECTORY "${GENERATE_DIR}")
    set(PROTO_META_BASE_DIR ${GENERATE_DIR})
else ()
    file(MAKE_DIRECTORY ${GENERATE_DIR})
    set(PROTO_META_BASE_DIR ${GENERATE_DIR})
endif ()

# 设置 proto 搜索路径
set(PROTO_FLAGS ${PROJECT_SOURCE_DIR}/proto)
# 获取 proto 文件
file(GLOB_RECURSE PROTO_SOURCE_FILES ${PROTO_FLAGS}/*.proto)

#message(NOTICE "PROTO_FLAGS: ${PROTO_FLAGS}")
#message(NOTICE "PROTO_SOURCE_FILES: ${PROTO_SOURCE_FILES}")
#message(NOTICE "PROTO_META_BASE_DIR: ${PROTO_META_BASE_DIR}")

foreach (proto_file ${PROTO_SOURCE_FILES})
    get_filename_component(FILE_NAME_WE ${proto_file} NAME_WE)
    get_filename_component(FILE_DIR ${proto_file} DIRECTORY)
    #    message(notice "FILE_NAME_WE: ${FILE_NAME_WE}")
    #    message(notice "FILE_DIR: ${FILE_DIR}")

    set(CUR_PROTO_SRCS "${PROTO_META_BASE_DIR}/${FILE_NAME_WE}.pb.cc")
    set(CUR_PROTO_HDRS "${PROTO_META_BASE_DIR}/${FILE_NAME_WE}.pb.h")
    set(CUR_PROTO_RPC_SRCS "${PROTO_META_BASE_DIR}/${FILE_NAME_WE}.grpc.pb.cc")
    set(CUR_PROTO_RPC_HDRS "${PROTO_META_BASE_DIR}/${FILE_NAME_WE}.grpc.pb.h")

    list(APPEND PROTO_SRC_CXX_ALL ${CUR_PROTO_SRCS} ${CUR_PROTO_HDRS}
            ${CUR_PROTO_RPC_SRCS} ${CUR_PROTO_RPC_HDRS})

endforeach ()

#message(NOTICE "PROTOBUF_PROTOC_EXECUTABLE: ${PROTOBUF_PROTOC_EXECUTABLE}")

# 自定义命令
add_custom_command(
        OUTPUT
        ${PROTO_SRC_CXX_ALL}
        COMMAND
        ${_PROTOBUF_PROTOC}
        ARGS
        -I ${PROTO_FLAGS}
        --cpp_out ${PROTO_META_BASE_DIR}
        --grpc_out ${PROTO_META_BASE_DIR}
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        ${PROTO_SOURCE_FILES}
        DEPENDS ${PROTO_SOURCE_FILES}
        COMMENT "Running C++ protocol buffer compiler"
)


add_custom_target(
        generate_proto
        DEPENDS ${PROTO_SRC_CXX_ALL}
)

# 设置生成源文件包含目录变量供上层引用
set(PROTO_GEN_INCLUDE_DIRS ${PROTO_META_BASE_DIR} PARENT_SCOPE)

#message(NOTICE "PROTO_SRCS: ${PROTO_SRCS}")

# 将生成的文件打包为库
# 程序可以链接到该库
add_library(proto_gen ${PROTO_SRC_CXX_ALL})
target_link_libraries(proto_gen
        ${_REFLECTION}
        ${_GRPC_GRPCPP}
        ${_PROTOBUF_LIBPROTOBUF})
add_dependencies(proto_gen generate_proto)

